from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.controllers.appointment.space import appointment_space_controller
from app.controllers.saas.buckling import buckling_controller
from app.controllers.saas.buckling_detail import buckling_detail_controller
from app.controllers.saas.buckling_todo import buckling_todo_controller
from app.controllers.saas.cases import cases_controller
from app.controllers.system.user import user_controller
from app.models import Goods, GoodsSku, CustomerUser, Cases, AppointmentDesigner, Buckling
from app.schemas.base import Success, SuccessExtra,Fail
from app.core.dependency import DependCustomerAuth
from app.schemas.saas import CasesCreate, BucklingSelect
from app.core.ctx import CTX_USER_ID

saas_buckling_router = APIRouter()

@saas_buckling_router.get("/list_buckling", summary=f"用户疗程项目", dependencies=[DependCustomerAuth])
async def list_buckling(
        page: int = Query(1, description="页码"),
        page_size: int = Query(1000, description="每页数量"),
        user_id: int = Query(None, description="用户"),
        name: str = Query('', description="商品名称"),
):
    q = Q(user_id=user_id,last_nums__gt=0)

    search_goods_ids = []
    if name:
        search_goods = await Goods.filter(name__contains=name).values("id")
        search_goods_ids = {good['id'] for good in search_goods}  # 获取所有的 goods_id
        q &= Q(goods_id__in=search_goods_ids)
    total, data = await buckling_controller.do_list(page=page, page_size=page_size, search=q)
    goods_ids = {goods['goods_id'] for goods in data}  # 获取所有的 goods_id
    sku_ids = {sku['sku_id'] for sku in data}  # 获取所有的 goods_id
    goods = await Goods.filter(id__in=goods_ids)
    goods_dict = {good.id: good.name for good in goods}
    goods_dict_cover = {good.id: good.cover for good in goods}
    skus = await GoodsSku.filter(id__in=sku_ids)
    skus_dict = {sku.id: sku.sku_name for sku in skus}
    for item in data:
        item['goods_name'] = goods_dict.get(item['goods_id'], "已删除商品")
        item['goods_cover'] = goods_dict_cover.get(item['goods_id'], "")
        item['sku_name'] = skus_dict.get(item['sku_id'], "已删除规格")
        item['select_nums'] = 0
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@saas_buckling_router.get("/list_buckling_goods", summary=f"用户新划扣项目", dependencies=[DependCustomerAuth])
async def list_buckling1(
        page: int = Query(1, description="页码"),
        page_size: int = Query(1000, description="每页数量"),
        user_id: int = Query(None, description="用户"),
        name: str = Query('', description="商品名称"),
        buckling_type: int = Query(0, description="类别"),
):
    q = Q(user_id=user_id)
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    if user.space_id:
        q &= Q(space_id__in=user.space_id)
    if buckling_type:
        q &= Q(type=buckling_type)
    total, data = await buckling_todo_controller.do_list_buckling(page=page, page_size=page_size,name=name, search=q)

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@saas_buckling_router.post("/create", summary=f"创建划扣", dependencies=[DependCustomerAuth])
async def do_create(
        data_in: CasesCreate,
):
    add_uid = CTX_USER_ID.get()
    data_in.add_uid = add_uid

    ret = await cases_controller.do_create(obj_in=data_in)

    if ret:
        return Success(msg="划扣成功")
    else:
        return Fail(msg="不足划扣,请检查或者刷新")

@saas_buckling_router.get("/get_group", summary=f"获取该卡的可以开的组合")
async def get_group(
        data_id: int = Query(..., description="ID"),
):
    data = await buckling_todo_controller.do_get_group(data_id=data_id)
    return SuccessExtra(data=data)

@saas_buckling_router.post("/start", summary=f"开卡", dependencies=[DependCustomerAuth])
async def do_start(
        data_in:BucklingSelect,
):
    add_uid = CTX_USER_ID.get()
    data_in.add_uid = add_uid
    data = await buckling_todo_controller.do_start(obj_in=data_in)
    if data["code"] == 1:
        return Success(msg=data["msg"])
    else:
        return Fail(msg=data["msg"])

@saas_buckling_router.get("/change_nums", summary=f"修改项目可使用数量")
async def update_nums(
        buckling_id: int = Query(1, description="buckling_id"),
        nums: int = Query(1, description="数量"),
):
    await Buckling.filter(id=buckling_id).update(last_nums=nums)
    return Success(msg="修改成功")

@saas_buckling_router.get("/list_buckling_detail", summary=f"划扣明细", dependencies=[DependCustomerAuth])
async def list_buckling_detail(
        page: int = Query(1, description="页码"),
        page_size: int = Query(1000, description="每页数量"),
        user_name: str = Query(None, description="客户"),
        space_id: int = Query(0, description="门店id"),
        start_time: str = Query('', description="开始时间"),
        end_time: str = Query('', description="结束时间"),
):
    q = Q()
    search_user_ids = []

    if user_name:
        search_users = await CustomerUser.filter(    Q(name__contains=user_name) | Q(phone__contains=user_name)).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    search_goods_ids = []
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    q = Q()
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    if user.space_id:
        q &= Q(space_id__in=user.space_id)
    if start_time and end_time:
        q &= Q(pay_time__range=[start_time, end_time])
    elif start_time:
        q &= Q(pay_time__gte=start_time)
    elif end_time:
        q &= Q(pay_time__lte=end_time)

    total, data = await cases_controller.do_list(page=page, page_size=page_size, search=q)
    user_ids = {detail['user_id'] for detail in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user for user in users}
    space_objs = await appointment_space_controller.level_list()

    for item in data:
        item['space_name'] = space_objs[item["space_id"]]
        user = users_dict.get(item['user_id'])
        if user:
            item['user_name'] = user.name
            item['user_phone'] = user.phone
        else:
            item['user_name'] = "用户已被删除"
            item['user_phone'] = ""
        designer_ids = item['designer_ids']  ##[1,2,3]
        item['designer_names'] = ""
        designers = await AppointmentDesigner.filter(id__in=designer_ids).all().values()
        item['designer_names'] = []
        for designer in designers:
            item['designer_names'].append(designer['name'])


    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)
